package com.mrobuy.jd;

import com.jd.open.api.sdk.DefaultJdClient;
import com.jd.open.api.sdk.JdClient;
import com.mrobuy.jdvc.dao.JDAccountDao;
import com.mrobuy.jdvc.entity.JDAccount;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import sun.security.util.Cache;

import javax.annotation.PostConstruct;
import java.util.Map;

@Component
public class JdClientFactory {

    private static JDAccountDao accountDao;

    private static Cache<String, JdClient> cache = Cache.newHardMemoryCache(0,3600 * 12);



    public static String serverUrl = "https://api.jd.com/routerjson";

    public static String _appKey = "FEAFBABCDEEC48A569A10818138D7841";
    public static String _appSecret = "36c196b5b2ea4c2aaaae6d80010a28a8";
    public static String _accessToken = "1d4a07ea9743455d99c2f7f63e2f7971a3zw";
    private static JdClient _client=new DefaultJdClient(serverUrl, _accessToken, _appKey,  _appSecret);

    @Autowired
    private JDAccountDao jdAccountDao;

    @PostConstruct
    public void init(){
        accountDao = jdAccountDao;
    }

    public static void clean(){
        cache.clear();
    }


    public static JdClient jdClient(){

        return jdClient("FEAFBABCDEEC48A569A10818138D7841");
    }

    public static JdClient jdClient(String appkey){

        JdClient client =  cache.get(appkey);
        if ( client!=null ) {
            return client;
        }


        if ( accountDao==null ) {
            return _client;
        }

        JDAccount account = accountDao.load(appkey);
        if ( account==null ) {
            return null;
        }

        client=new DefaultJdClient(serverUrl, account.getAccess_token(),  account.getAppkey(), account.getAppsecret());

        cache.put(appkey, client);

        return client;
    }

}
